package com.emm.yixun.mobile.ui.customer;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.ui.from.NewFromActivity;
import com.emm.yixun.mobile.ui.signed.NewSignedActivity;
import com.emm.yixun.mobile.ui.subscribe.NewSubscribeActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.HashMap;
import java.util.Map;

import xf.tools.Loading;

public class TipsActivity extends BaseActivity {

    private static final String TAG = "TipsActivity";

    /**
     * 标题
     */
    TextView tvTitle;

    /**
     * 返回按钮
     */
    ImageView btBack;

    /**
     * 提示信息1
     */
    TextView tvTipsLines1;

    /**
     * 提示信息2
     */
    TextView tvTipsLines2;

    /**
     * 备注类容
     */
    EditText etContent;

    /**
     * 填备注保存
     */
    TextView btSave;

    /**
     * 按实际意向等级保存
     */
    TextView btCancel;

    TextView tvErrorTips;

    private int openType;//0新增

    private String customerId;

    private String intention;

    /**
     * 是否可以修改用户意向等级（0不能 1可以）
     */
    private int isEditUserLv;

    int fromOpenType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tips);
        openType = getIntent().getIntExtra("openType", 0);
        customerId = getIntent().getStringExtra("customerId");
        isEditUserLv = getIntent().getIntExtra("isEditUserLv", 1);
        fromOpenType = getIntent().getIntExtra("fromOpenType", -1);
        initView();
        initBtn();
    }

    private String getValue(String str) {
        String result = "";
        switch (str) {
            case "1":
                result = "A+";
                break;
            case "2":
                result = "A";
                break;
            case "3":
                result = "B";
                break;
            case "4":
                result = "C";
                break;
            case "5":
                result = "D";
                break;
        }
        return result;
    }

    private String getKey(String str) {
        String result = "";
        switch (str) {
            case "A+":
                result = "1";
                break;
            case "A":
                result = "2";
                break;
            case "B":
                result = "3";
                break;
            case "C":
                result = "4";
                break;
            case "D":
                result = "5";
                break;
        }
        return result;
    }

    private void initView() {
        RelativeLayout tips = (RelativeLayout) findViewById(R.id.tips_include).findViewById(R.id.main_head_top_rela);
        SetViewHeight(tips);
        btBack = (ImageView) findViewById(R.id.back_btn);
        btBack.setVisibility(View.VISIBLE);
        tvTitle = (TextView) findViewById(R.id.title_main);
        tvTitle.setText(getString(R.string.customer_details));
        tvTipsLines1 = (TextView) findViewById(R.id.tv_tips_lines1);
        intention = getValue((String) EmmApplication.maps.get("intentionLevel"));
        tvTipsLines1.setText(String.format("填写信息不全不满足意向等级【%s】要求", intention));
        tvTipsLines2 = (TextView) findViewById(R.id.tv_tips_lines2);
        tvTipsLines2.setText(String.format("继续保存客户为意向等级【%s】", intention));
        tvErrorTips = (TextView) findViewById(R.id.tv_error_tips);
        etContent = (EditText) findViewById(R.id.et_content);
        btSave = (TextView) findViewById(R.id.bt_save);
        btCancel = (TextView) findViewById(R.id.bt_cancel);
        btCancel.setVisibility(isEditUserLv == 0 ? View.GONE : View.VISIBLE);
    }

    private void initBtn() {
        btBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    tvErrorTips.setText("");
                }
            }
        });
        btSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!EmmApplication.isNull(etContent.getText().toString().trim())) {
                    tvErrorTips.setText("请输入有效的备注内容");
                    return;
                }
                sendHttp(intention);
            }
        });
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendHttp("");
            }
        });
    }

    private void sendHttp(String str) {
        Map<String, Object> map = EmmApplication.maps;
        if (EmmApplication.isNull(etContent.getText().toString())) {
            map.put("intentionLevelRemark", etContent.getText().toString());
        }
        if (openType == 0) {
            EmmApplication.updateUrl("addCustomer");
            map.put("projectId", EmmApplication.getProjectID());
        } else {
            EmmApplication.updateUrl("editCustomer");
            map.put("customerId", customerId);
        }
        map.put("intentionLevel", getKey(str));
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("params", EmmApplication.maps);
        JSONObject json = new JSONObject(paramsMap);
        final String jsonStr = json.toString();
        final RequestParams params = new RequestParams();
        params.put("body", jsonStr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                Loading.hideDialogForLoading();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                Loading.hideDialogForLoading();
            }

            @Override
            public void onStart() {
                super.onStart();
                Loading.showDialogForLoading(TipsActivity.this, "正在加载...", false, true, 60000);
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                Loading.hideDialogForLoading();
                if (!EmmApplication.isNull(content)) {
                    return;
                }
                if (EmmApplication.isNull(String.valueOf(EmmApplication.maps.get("intentionLevel")))) {
                    if (null != EmmApplication.details) {
                        EmmApplication.details.setIntentionLevel("A");
                    }
                } else {
                    if (null != EmmApplication.details) {
                        EmmApplication.details.setIntentionLevel("");
                    }
                }
                Log.v(TAG, content);
                if (openType == 0) {
                    EmmApplication.T("新增成功");
                    EmmApplication.IS_RELOAD = true;
                    EmmApplication.IS_FINISH_DETAILS = true;
                } else {
                    EmmApplication.T("修改成功");
                    EmmApplication.IS_RELOAD_DETAILS = true;
                    EmmApplication.IS_FINISH_DETAILS = true;
                }
                startActivity();
                finish();
            }
        });
    }

    private void startActivity() {
        Intent intent = new Intent();
        intent.putExtra("customerId", customerId);
        switch (fromOpenType) {// 1 认筹 2认购 3签约
            case 1:// 新增认筹
                EmmApplication.IsLoadingFromList = true;
                intent.setClass(TipsActivity.this, NewFromActivity.class);
                startActivity(intent);
                break;
            case 2: // 新增认购
                EmmApplication.IsLoadingFromList = true;
                intent.putExtra("OpenType", "1");
                intent.setClass(TipsActivity.this, NewSubscribeActivity.class);
                startActivity(intent);
                break;
            case 3: // 新增签约
                EmmApplication.IsLoadingFromList = true;
                intent.putExtra("OpenType", "1");
                intent.setClass(TipsActivity.this, NewSignedActivity.class);
                startActivity(intent);
                break;
        }
    }

}
